package com.example.userservice.Controller;


import com.example.common.domain.Result;
import com.example.common.domain.pojo.Student;
import com.example.common.domain.pojo.Teacher;
import com.example.common.domain.pojo.User;
import com.example.common.utils.MD5Util;
import com.example.common.utils.UserContext;
import com.example.userservice.domain.dto.*;
import com.example.userservice.domain.vo.UserTokenVo;
import com.example.userservice.service.AuthService;
import com.example.userservice.service.StudentService;
import com.example.userservice.service.TeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Api(value = "登录接口", description = "用户相关操作")
@RestController
@RefreshScope//时时刷新配置信息
@Slf4j  //日志  log.info("登录日志测试：");
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    @Autowired
    private AuthService authService;
@Autowired
private TeacherService teacherService;
@Autowired
private StudentService studentService;

    /**
     * 用户登录
     *
     * @param user 用户信息
     */
    @ApiOperation(value = "登录   ", notes = "作用：账号密码登录")
    @PostMapping("/login") //方法名
    public Result<UserTokenVo> login(@ApiParam(value = "解释参数含意", required = true) @RequestBody User user) throws NoSuchAlgorithmException {
        log.info("登录日志测试：");
        Map<String, String> toKenMap = new HashMap();
        String MD5 = MD5Util.encrypt(user.getPassword());
        User us = authService.PasToUser(String.valueOf(user.getId()), MD5);
        Teacher teacher=null;
        Student student=null;
        if (us != null) {
            if(us.getRole().getDesc().equals("0")||us.getRole().getDesc().equals("student")||us.getRole().getDesc().equals("STUDENT"))
                  student=studentService.getStudentById(String.valueOf(us.getId()));
            else if(us.getRole().getDesc().equals("1")||us.getRole().getDesc().equals("teacher")||us.getRole().getDesc().equals("TEACHER"))
                  teacher=teacherService.getTeacherById(String.valueOf(us.getId()));
            toKenMap=authService.AddToken(String.valueOf(us.getId()), us.getRole().getDesc());//保存token
        }
        else
            Result.error("用户不存在");
        return Result.success(new UserTokenVo(us, toKenMap,student,teacher));
    }

    /**
     * 退出登录
     *
     * @param id 用户id
     */
    @GetMapping("/exit/{id}")  // 退出登录
    public Result<Object> exit(@PathVariable String id) {
        boolean isLoggedOut = authService.logOut(id);
        if (isLoggedOut) {
            return Result.success("成功退出登录");
        } else {
            return Result.error("后端登录问题");
        }
    }


//    @PostMapping("/register")  // 修改密码(忘记密码)
//    public Result<Object> changePassword(@RequestBody PasDto pasDto) throws NoSuchAlgorithmException {
//        String OldMD5= MD5Util.encrypt(pasDto.getOldPassword());
//        User isValid = authService.PasToUser(String.valueOf(pasDto.getId()), OldMD5);
//        if (isValid==null) {
//            return Result.error("原密码输入错误");
//        }
//        // 2. 验证通过后，更新用户的密码
//        String NewMD5= MD5Util.encrypt(pasDto.getNewPassword());
//        boolean isPasswordUpdated = authService.updatePassword(String.valueOf(pasDto.getId()), NewMD5);  // 假设你有一个更新密码的方法
//        if (isPasswordUpdated) {
//            return Result.success("密码修改成功");
//        } else {
//            return Result.error("密码修改失败，请稍后重试");
//        }
//    }

    /**
     * 获取验证码登录
     * @param phone 手机号
     */
    @GetMapping("/login/{phone}")  // 获取验证码登录
    public Result<Void> getStoreDate(@PathVariable String phone) throws MessagingException {
        authService.sendLoginCode(phone);
        return Result.success();
    }

    /**
     * 验证码登录成功
     * @param t 手机号和验证码
     */
    @PostMapping("/login/phone")  //验证码登录成功
    public Result<UserTokenVo> getStoreDate(@RequestBody PhoneLoginDto t) throws MessagingException {
        UserTokenVo userTokenVo=new UserTokenVo();
        if (authService.verifyLoginCode(t.getPhone(), t.getCode())) {
            User us=authService.getPhone(t.getPhone());
            userTokenVo.setUser(us);
            log.info("验证码登录日志测试：");
            Map<String, String> toKenMap = new HashMap();
            if (us != null) {
                if(us.getRole().getDesc().equals("0")||us.getRole().getDesc().equals("student")||us.getRole().getDesc().equals("STUDENT"))
                    userTokenVo.setStudent(studentService.getStudentById(String.valueOf(us.getId())));
                else if(us.getRole().getDesc().equals("1")||us.getRole().getDesc().equals("teacher")||us.getRole().getDesc().equals("TEACHER"))
                    userTokenVo.setTeacher(teacherService.getTeacherById(String.valueOf(us.getId())));
                userTokenVo.setToken(authService.AddToken(String.valueOf(us.getId()), us.getRole().getDesc()));//保存token
            }
            return Result.success(userTokenVo);
        } else
            return Result.error("验证码错误或者验证码过期或者手机号未绑定");
    }

    /**
     * 发送修改手机号的验证码（old手机号验证码）
     * @param phoneCodeDto 手机号和验证码
     */
    @GetMapping("/sendOldPhoneCode")  // 发送修改手机号的验证码
    public Result<Object> sendOldPhoneCode(@RequestBody PhoneCodeDto phoneCodeDto) throws MessagingException {
        return authService.sendOldPhoneCode(phoneCodeDto.getId(), phoneCodeDto.getOldPhone());
    }

    /**
     * old手机号验证码接受
     * @param phoneCodeDto
     */
    @PostMapping("/update/oldPhone/code}")  // 更改手机号
    public Result<Object> OldPhone(@RequestBody PhoneCodeDto phoneCodeDto) throws MessagingException {
        return Result.success(authService.OldPhone(phoneCodeDto.getId(), phoneCodeDto.getOldPhone(), phoneCodeDto.getCode()));
    }


    /**
     * 发送修改手机号的验证码（验证码有效时间都是五分钟）
     * @param phoneCodeDto 手机号和验证码
     */
    @GetMapping("/sendModifyPhoneCode")  // 发送修改手机号的验证码
    public Result<Object> sendModifyPhoneCode(@RequestBody PhoneCodeDto phoneCodeDto) throws MessagingException {
        return authService.sendModifyPhoneCode(phoneCodeDto.getId(), phoneCodeDto.getNewPhone());
    }

    /**
     * 更改手机号
     * @param phoneCodeDto 用户id,新手机号和验证码
     */
    @PostMapping("/update/phone/code}")  // 更改手机号
    public Result<Object> modifyPhone(@RequestBody PhoneCodeDto phoneCodeDto) throws MessagingException {
        return Result.success(authService.modifyPhone(phoneCodeDto.getId(), phoneCodeDto.getNewPhone(), phoneCodeDto.getCode()));
    }

    /**
     * 更新密码
     *
     * @param pas id,旧密码，新密码
     * @return
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("/update/password")  // 更新密码
    public Result<Object> sendModifyPhoneCode(@RequestBody PasDto pas) throws NoSuchAlgorithmException {
        User user = authService.PasToUser(String.valueOf(pas.getId()), MD5Util.encrypt(pas.getOldPassword()));
        if (user == null)
            return Result.error("原密码输入错误");
        else {
            authService.updatePassword(pas.getId(), MD5Util.encrypt(pas.getNewPassword()));
            return Result.success("密码修改成功");
        }
    }

    /**
     * 忘记密码获取验证码
     * @param t 手机号
     */
    @PostMapping("/reset/pas/code")   //忘记密码
    public Result<Object> sendResetPasswordCode(@RequestBody ResetPhoneDto t) {
        return authService.sendResetPasswordCode(t.getPhone());
    }

    /**
     * 忘记密码后修改密码
     *
     * @param t 手机号和验证码
     */
    @PostMapping("/reset/pas")  //忘记密码后修改密码
    public Result<Object> resetPassword(@RequestBody ResetPhoneDto t) throws NoSuchAlgorithmException {
        return authService.resetPassword(t.getPhone(), t.getCode(), t.getNewPassword());
    }


    /**
     * 绑定手机号发送验证码
     * @param phone 手机号
     */
    @GetMapping("/bind/code/{phone}")
    public Result<Void> bindPhoneCode(@PathVariable String phone) {
        System.out.println("绑定手机号发送验证码");
        authService.getBingPhoneCode(phone);
        return Result.success();
    }

    /**
     * 绑定手机号
     * @param t 手机号和验证码
     */
    @PostMapping("/bind/phone")
    public Result<Object> bindPhone(@RequestBody BindPhoneDto t) throws NoSuchAlgorithmException {
        return authService.BingPhone(t.getId(), t.getPhone(), t.getCode());
    }

    /**
     * 更新用户头像
     * @param avatarFile 用户头像文件
     * @param userId     用户id
     */
    @PostMapping("/update/img")
    public Result<Object> updateAvatar(@RequestParam("avatarFile") MultipartFile avatarFile,
                                       @RequestParam("userId") String userId) throws NoSuchAlgorithmException {
        System.out.printf("UserContext:" + UserContext.getUser());
        return authService.updateAvatar(userId, avatarFile);
    }

    /**
     * 人脸登录
     * @param t 人脸信息
     */
    @PostMapping("/login/face")
    public Result<User> faceLogin(@RequestParam FaceDto t) {
        return authService.faceLogin(t.getId(), t.getImage());
    }


}
